<template>
	<xn-form-container
		:title="formData.id ? '编辑商品盒子' : '增加商品盒子'"
		:width="700"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="horizontal">
			<a-form-item label="分类：" name="categoryId">

				<a-tree-select
					v-model:value="formData.categoryId"
					style="width: 100%"
					:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
					placeholder="请选择上级机构"
					allow-clear
					tree-default-expand-all
					:tree-data="treeData"
					:field-names="{
						children: 'children',
						label: 'name',
						value: 'id'
					}"
					selectable="false"
					tree-line
				/>
			</a-form-item>
			<a-form-item label="商品盒子名称：" name="goodsBoxName">
				<a-input v-model:value="formData.goodsBoxName" placeholder="请输入商品盒子名称" allow-clear />
			</a-form-item>
			<a-form-item label="商品盒子详情：" name="goodsBoxDetail">
				<a-textarea :rows="8"  v-model:value="formData.goodsBoxDetail" placeholder="请输入商品盒子详情" allow-clear />
			</a-form-item>
			<a-form-item v-if="formData.goodsBoxImgUrl" label="更换封面：" name="isChangeImg">
				<a-radio v-model:checked="formData.isChangeImg">重新上传盒子封面</a-radio>
			</a-form-item>
			<a-form-item label="盒子封面：" name="goodsBoxImgUrl">
				<div class="clearfix">
					<a-upload
						v-model:file-list="fileList"
						:beforeUpload="beforeUpload"
						list-type="picture-card"
						@preview="handlePreview"
					>
						<div v-if="fileList.length < 1">
							<plus-outlined />
							<div style="margin-top: 8px">Upload</div>
						</div>
					</a-upload>
					<a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
						<img alt="example" style="height:800px;width: 100%" :src="previewImage" />
					</a-modal>
				</div>
			</a-form-item>
			<a-form-item label="售价：" name="goodsBoxPriceFee">
				<a-input-number
					v-model:value="formData.goodsBoxPriceFee"
					placeholder="请输入售价"
					:min="1"
					:max="10000"
					style="width: 100%"
				/>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="bizGoodsBoxForm">
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import bizGoodsBoxApi from '@/api/biz/bizGoodsBoxApi'
	import { message, Upload } from 'ant-design-vue'
	import bizCategoryApi from "@/api/biz/bizCategoryApi";
	// 抽屉状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	// 表单数据
	const formData = ref({})
	const submitLoading = ref(false)

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		if (record) {
			let recordData = cloneDeep(record)
			formData.value = Object.assign({}, recordData)
			// 编辑的情况展示选择框

		}

		// 获取机构树并加入顶级
		bizCategoryApi.tree().then((res) => {
			treeData.value = [
				{
					id: 0,
					parentId: '0',
					name: '全部',
					children: res
				}
			]
		})
	}
	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		formData.value = {}
		visible.value = false
	}
	// 默认要校验的
	const formRules = {
		goodsBoxName: [required('请输入商品盒子名称')],
		goodsBoxDetail: [required('请输入详情')],
		goodsBoxPriceFee: [required('请输入售价')],
		categoryId: [required('请选择分类')],
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			let id = formData.value.id;
			submitLoading.value = true
			submitLoading.value = false
			const res = new FormData();
			// 新增
			if (id==null){
				res.append('goodsBoxImgUrl', currFile.value);
			}
			// 更新
			else {
				res.append("isChangeImg", formData.value.isChangeImg?"YES":"NO")
				if (formData.value.isChangeImg){
					res.append('goodsBoxImgUrl', currFile.value);
				}
			}
			res.append("goodsBoxName",formData.value.goodsBoxName)
			res.append("goodsBoxDetail",formData.value.goodsBoxDetail)
			res.append("goodsBoxPriceFee",formData.value.goodsBoxPriceFee)
			res.append("id",id)
			res.append("categoryId",formData.value.categoryId)
			bizGoodsBoxApi
				.bizGoodsBoxSubmitForm(res,id)
				.then(() => {
					onClose()
					emit('successful')
				})
				.finally(() => {
					submitLoading.value = false
				})
		})
	}
	// 抛出函数
	defineExpose({
		onOpen
	})
	const beforeUpload = (file) => {
		const isPNG =( file.type === 'image/png'||  file.type === 'image/jpeg')
		if (!isPNG) {
			message.error(`${file.name}暂且只支持png和jpg图片格式`)
			return false
		}
		currFile.value=file
		fileList.value = [...(fileList.value || []), file];
		return false;
	}
	function getBase64(file) {
		return new Promise((resolve, reject) => {
			const reader = new FileReader();
			reader.readAsDataURL(file);
			reader.onload = () => resolve(reader.result);
			reader.onerror = error => reject(error);
		});
	}
	const previewVisible = ref(false);
	const previewImage = ref('');
	const previewTitle = ref('');
	// 文件上传
	const fileList = ref([]);
	const handleCancel = () => {
		previewVisible.value = false;
		previewTitle.value = '';
	};
	const currFile =ref(null)

	const handlePreview = () => {
		previewVisible.value = true;
		getBase64(currFile.value).then(x=>{
			previewImage.value=x
			previewTitle.value = currFile.value.name;
		})
	};
	// 树
	const treeData = ref([])

</script>
